package com.iapcursos.portal.procefet.utils;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {
	
	private int inicio;
	private int fim;
	private String temp = "";
	
	public String clearImageTag(String conteudo){
		if(conteudo.contains("<img")){
			inicio = conteudo.indexOf("<img");
			fim = conteudo.indexOf("/>", inicio) + 2;
			
			temp = conteudo.substring(inicio, fim);
	
			conteudo = conteudo.replace(temp, "");
			
			this.clearImageTag(conteudo);
		}
		
		return conteudo;
	}
	

	public File[] getFilesByDirectory(String directory){
		File dir = new File(directory);
		File[] files;
	    
	    FileFilter fileFilter = new FileFilter() {
	        public boolean accept(File file) {
	            return !file.isDirectory();
	        }
	    };
	    
	    files = dir.listFiles(fileFilter);
	    
		return files;
	}
	
	public List<String> getDirectories(String directory) {
		File dir = new File(directory);
		File[] directories;
	    
	    FileFilter fileFilter = new FileFilter() {
	        public boolean accept(File file) {
	            return file.isDirectory();
	        }
	    };
	    
	    directories = dir.listFiles(fileFilter);
	    List<String> directoriesToReturn = new ArrayList<String>();
	    
	    for (File directorie : directories) {
			directoriesToReturn.add(directorie.getName());
		}

		return directoriesToReturn;
	}
	
	public static void copyFile(File file, String filename, String dir){
		File originalFile = file;
		
		File outPutFile = new File(dir + filename);
		
		try {
			InputStream in = new FileInputStream(originalFile);
			OutputStream out = new FileOutputStream(outPutFile);
			
			byte[] buf = new byte[1024*10];
			int len;
			
			while ((len = in.read(buf)) > 0){
		        out.write(buf, 0, len);
		    }
			
			in.close();
		    out.close();
		    
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static boolean inputStreamToFile(InputStream is, File arquivo)
    {
		try
		{
			OutputStream out=new FileOutputStream(arquivo);
			byte buf[]=new byte[1024];
			int len;
			while((len=is.read(buf))>0)
				out.write(buf,0,len);
			out.close();
			is.close();
			return true;
		}
		catch (IOException e){
			e.printStackTrace();
			return false;
		}
    }
	
   
}
